package org.jeecg.modules.iot.aio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.utils.lock.MapWithLock;

import java.util.HashMap;
import java.util.Objects;

/**
 * 这里是一个注释
 *
 * @author scw
 * @version v1.0
 * @date
 */
public class QueueList {

    private static Logger log = LoggerFactory.getLogger(QueueList.class);

    /**
     * sn
     */
    private MapWithLock<String, ChannelContext> macMap = new MapWithLock<>(new HashMap<String, ChannelContext>());

    private String rwKey = "_aio_macs__";

    public void bind(ChannelContext channelContext) {
        if (channelContext == null) return;

        String mac = channelContext.getRentboxSN();
        if(mac == null) return;
        if(Objects.equals(mac, ChannelContext.UNKNOWN_ADDRESS_IP)) return;
        try {
            macMap.put(mac,channelContext);
        }catch (Exception e){
            e.printStackTrace();
            log.error("绑定出错，当前MAC:{}，错误信息：{}",mac,e.getMessage());
        }
    }
    public void unbind(ChannelContext channelContext){
        if (channelContext == null) return;
        String mac = channelContext.getRentboxSN();
        try {
            if(mac == null) return;
            macMap.remove(mac);
        }catch (Exception e){
            log.error("解绑出错，当前MAC:{}，错误信息：{}",mac,e.getMessage());
        }
    }

    public MapWithLock<String, ChannelContext> getMacMap(){
        return this.macMap;
    }

    public ChannelContext getChannelContext(String sn,AioConfiguration aioConfiguration){
        ChannelContext channelContext = macMap.get(sn);
        if(channelContext == null) {
            channelContext = new ChannelContext(aioConfiguration, sn);
            this.bind(channelContext);
        }
        return channelContext;
    }


}
